package org.linlinjava.litemall.web.service;

import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallOrderCash;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallOrderCashService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

import static org.linlinjava.litemall.web.util.WebResponseCode.AUTH_INVALID_USER;
import static org.linlinjava.litemall.web.util.WebResponseCode.INVALID_RECHARGE_AMOUNT;

@Service
public class WebUserService {
    @Autowired
    private LitemallUserService litemallUserService;

    @Autowired
    private LitemallOrderCashService litemallOrderCashService;

    public ResponseUtil.Response<LitemallUser> recharge(Integer userId, BigDecimal amount){
        LitemallUser user = litemallUserService.findById(userId);

        if(amount.subtract(BigDecimal.ZERO).compareTo(BigDecimal.ZERO) <= 0){
            return ResponseUtil.fail(INVALID_RECHARGE_AMOUNT,"充值金额不正确");
        }

        if(user == null){
            return ResponseUtil.fail(AUTH_INVALID_USER,"用户不存在");
        }else{
            user.setAvailableAmount(user.getAvailableAmount().add(amount));
            litemallUserService.updateById(user);

            LitemallOrderCash cash = new LitemallOrderCash();
//            cash.setOrderId(order.getId());
            amount = canadaRoundup(amount);
//            cash.setOrderPrice(amount);
            cash.setCash(amount);
            cash.setChange(BigDecimal.ZERO);
            cash.setAddUserId(userId);
            cash.setAddUserName(litemallUserService.findById(userId).getUsername());
            litemallOrderCashService.add(cash);

            return ResponseUtil.ok(user);
        }
    }

    public BigDecimal canadaRoundup(BigDecimal price) {
        BigDecimal a = price.multiply(BigDecimal.TEN).setScale(1, BigDecimal.ROUND_HALF_UP);
        BigDecimal b = a.remainder( BigDecimal.ONE );
        if(b.compareTo(new BigDecimal(0.2).setScale(1, BigDecimal.ROUND_HALF_UP)) <= 0) {
            a = a.subtract(b);
        }else if(b.compareTo(new BigDecimal(0.7).setScale(1, BigDecimal.ROUND_HALF_UP)) <= 0){
            a = a.subtract(b).add(new BigDecimal(0.5));
        }else {
            a = a.subtract(b).add(new BigDecimal(1));
        }

        a = a.divide(BigDecimal.TEN).setScale(2, BigDecimal.ROUND_HALF_UP);
        return a;
    }
}
